package com.xinyu126.net_trace.share.layers

import android.content.Context
import android.util.Log
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.BitmapDescriptorFactory
import com.baidu.mapapi.map.MarkerOptions
import com.baidu.mapapi.map.OverlayOptions
import com.baidu.mapapi.model.LatLng
import com.magical.location.LocationDatabaseManager
import com.magical.location.model.Client
import com.xinyu126.net_trace.R
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit


interface IMarker{

    fun start(context : Context)

    fun stop()
}
/**
 * 显示客户端的最后定位点
 * */
class ClientPointMarker(private val baiduMap: BaiduMap,private val myId:String)  : IMarker{
    private lateinit var executor: ScheduledExecutorService
    private lateinit var trackClients: List<Client>
    private var clientsJsonStr = "[]"
    override fun start(context : Context) {
        executor = Executors.newScheduledThreadPool(1)
        //查找数据库,获取定位点
        Log.d("ClientPointMarker", "start")
        executor.schedule({checkClients(context)},1, TimeUnit.SECONDS)

    }

    override fun stop() {
        executor.shutdown()
    }

    private fun checkClients(context: Context) {
        val database = LocationDatabaseManager(context)
        trackClients = database.getClients()
        if(trackClients.isEmpty()){
            Log.d("ClientPointMarker", "trackClients is empty")
            return
        }

        val strList = ArrayList<String>()
        for(client in trackClients){
            strList.add(client.clientId)
        }
        // json 格式 [string,string]
        clientsJsonStr = JSONArray(strList).toString()
        Log.d("ClientPointMarker", "clientsJsonStr: $clientsJsonStr")

        executor.scheduleWithFixedDelay({requestLocation()}, 0, 10, TimeUnit.SECONDS)
        executor.scheduleWithFixedDelay({test()}, 0, 10, TimeUnit.SECONDS)

    }

    private fun test(){
        Log.d("ClientPointMarker", "test")
    }
    private fun requestLocation() {
        try {

            Log.d("ClientPointMarker", "requestLocation")
            val client = OkHttpClient()
            val url = "http://www.xinyu126.com/api/child.trace/lastTrace"
            //json
            val request = Request.Builder().url(url).header("client-id", myId).post(clientsJsonStr.toRequestBody("application/json".toMediaTypeOrNull())).build()
            val response = client.newCall(request).execute()
            val responseBody = response.body?.string()
            Log.d("ClientPointMarker", "responseBody: $responseBody")
            // 解析 responseBody 为 json 对象
            if(responseBody.isNullOrEmpty()){
                Log.d("ClientPointMarker", "responseBody is empty")
                return
            }
            val jsonObject = JSONObject(responseBody)
            if(jsonObject.has("error")|| jsonObject.getInt("code") != 1){
                Log.d("ClientPointMarker", responseBody)
                return
            }
            val data = jsonObject.getJSONArray("data")
            Log.d("ClientPointMarker", "data: $data")
            //[{"client_id":"6eafc5dc-055f-46c3-9ce6-9679395093ab","longitude":121.596134,"latitude":38.917902,"speed":0,"create_time":1749005465320,"location_id":3817}]

            val options: MutableList<OverlayOptions> = ArrayList()
            for(i in 0 until data.length()){
                val cliObjet = data.getJSONObject(i)
                val lat = cliObjet.getDouble("latitude")
                val lng = cliObjet.getDouble("longitude")
                val laglng = LatLng(lat,lng)
                val clientId = cliObjet.getString("client_id")
                val trackClient = trackClients.find { it.clientId == clientId }
                var clientName = ""
                if(trackClient == null){
                    Log.d("ClientPointMarker", "client is null")
                }else{
                    clientName = trackClient.client_name
                }
                val bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.placeholder)
                val option = MarkerOptions().position(laglng).title(clientName).icon(bitmap)
                options.add(option)
            }
            Log.d("ClientPointMarker", "add options ${options.size}")
            baiduMap.clear()
            baiduMap.addOverlays(options)

        }catch (e:Throwable){
            Log.e("ClientPointMarker", "error  $e}")
        }
    }

}